package com.example.bookshop.controller;

import com.example.bookshop.bean.AdminBean;
import com.example.bookshop.bean.ResultBean;
import com.example.bookshop.dao.AdminDao;
import com.example.bookshop.dao.BookTypeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
public class AdminController {
    @Autowired
    private AdminDao adminDao;
    /**
     * 登录
     * @param account
     * @param pass
     */
    @RequestMapping("/login")
    public ResultBean login( String account, String pass, HttpSession session){
        ResultBean result = new ResultBean();
        AdminBean admin = adminDao.selectByAccountAndPass(account, pass);
        if (admin==null){
            //没查到数据
        result.setCode(-1);
        result.setMsg("账号或密码错误!");
        }else {
            //查到了数据
            result.setCode(1);
            result.setMsg("登陆成功!");
            result.setData(admin);
            //将登陆成功的用户放到session
            session.setAttribute("admin",admin);
        }
        return result;
    }

    @RequestMapping("/logout")
    public ResultBean logout(HttpSession session){
        ResultBean result = new ResultBean();
        result.setCode(1);//清空
        result.setMsg("退出成功!");
        session.invalidate();
        return result;
    }

    @RequestMapping("/modify_pass")
    public ResultBean modifyPass(String oldPass,String newPass,String confirmPass,HttpSession session){
        ResultBean result = new ResultBean();
        //获取登陆成功后的用户
        AdminBean admin = (AdminBean) session.getAttribute("admin");
        //旧密码是否正确
        AdminBean adminTemp = adminDao.selectByAccountAndPass(admin.getAccount(), oldPass);
        if (adminTemp==null){
            result.setCode(-1);
            result.setMsg("旧密码不正确!");
            return result;
        }
            //修改密码
        if (adminDao.updatePass(admin.getAccount(),newPass) == 1){
            result.setCode(1);
            result.setMsg("密码修改成功!");
        }else {
            result.setCode(-1);
            result.setMsg("密码修改失败!");
        }
        return  result;
    }

    @RequestMapping("updateAccount")
    public ResultBean updateAccount(String newAccount,String NickName,HttpSession session){
        ResultBean result = new ResultBean();
        //获取登陆成功的用户
        AdminBean admin = (AdminBean) session.getAttribute("admin");
        //修改用户信息
        if (adminDao.updateAccountAndNickName(admin.getAccount(), newAccount,NickName) >= 1){
            result.setCode(1);
            result.setMsg("修改成功!");
        }else{
            result.setCode(-1);
            result.setMsg("修改失败!");
        }
        return result;
    }
}
